import DuUtil from '../../utils/DuUtil'
import userStoreCreater from '../../store/userStore'
import cacheStoreCreater from '../../store/cacheStore'
import tabsStoreCreater from '../../store/tabsStore'
import menuStoreCreater from '../../store/menuStore'
import { menuPathMap } from './useAsyncRoute'

// 前置守卫
export function useBeforeEach() {
  const ifLogin = () => {
    const userStore = userStoreCreater()
    return userStore.token ? true : false
  }

  return {
    ifLogin,
  }
}

// 后置守卫
export function useAfterEach() {
  // 1.处理路由缓存
  const toCache = (to) => {
    const comp = to.matched[to.matched.length - 1].components
    comp.default.name = to.name // 设计成组件的name与路由的name保持一致 (因为keep-alive的:include匹配的是组件的name属性及comp.default.name)
    const cacheStore = cacheStoreCreater()
    if (to.meta.cache && !cacheStore.cacheNameArr.includes(to.name)) {
      cacheStore.addCacheName(to.name)
    }
  }

  // 设置menuId
  const setMenuId = (to) => {
    const menuStore = menuStoreCreater()
    const menu = menuPathMap.get(to.path)
    if (!DuUtil.isEmpty(menu)) {
      menuStore.menuId = menu.id
    } else {
      menuStore.menuId = ''
    }
  }

  // 2. 添加tab页
  const toAddTab = (to) => {
    const tabsStore = tabsStoreCreater()
    tabsStore.addTab(to)

    // 3. 设置menuid
    setMenuId(to)
  }
  return {
    toCache,
    toAddTab,
  }
}
